package cn.com.cifi.mars.web.action.masterDataToMars;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.entity.MdmBuildArea;
import cn.com.cifi.mars.entity.MdmGroupBld;
import cn.com.cifi.mars.entity.MdmProject;
import cn.com.cifi.mars.entity.MdmProjectPatner;
import cn.com.cifi.mars.entity.MdmStage;
import cn.com.cifi.mars.entity.MymContract;
import cn.com.cifi.mars.entity.MymRooms;
import cn.com.cifi.mars.entity.MymRooms2;
import cn.com.cifi.mars.service.BuildAreaService;
import cn.com.cifi.mars.service.GroupBldService;
import cn.com.cifi.mars.service.MdmService;
import cn.com.cifi.mars.service.MymContractService;
import cn.com.cifi.mars.service.MymRooms2Service;
import cn.com.cifi.mars.service.MymRoomsService;
import cn.com.cifi.mars.service.MymService;
import cn.com.cifi.mars.service.PanoplanBuildPlanItemDetailService;
import cn.com.cifi.mars.service.PanoplanBuildPlanItemService;
import cn.com.cifi.mars.service.PanoplanBuildPlanService;
import cn.com.cifi.mars.service.ProjectPatnerService;
import cn.com.cifi.mars.service.ProjectService;
import cn.com.cifi.mars.service.StagePartNersService;
import cn.com.cifi.mars.service.StageService;
import cn.com.cifi.mars.util.ListUtils;
import cn.com.cifi.mars.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class MasterDataToMarsController extends BaseAction implements IMasterDataToMarsController {

	private static final Logger logger = LoggerFactory.getLogger(MasterDataToMarsController.class);
	
	@Autowired
	private MdmService mdmService;
	
	@Autowired
	private StageService stageService;
	
	@Autowired
	private BuildAreaService buildAreaService;
	
	@Autowired
	private GroupBldService groupBldService;

	@Autowired
	private ProjectService projectService;
 
	@Autowired
    private ProjectPatnerService projectPatnerService;
	
	@Autowired
	private StagePartNersService stagePartNersService;
	
	@Autowired
	private MymService mymService;
	
	@Autowired
	private MymContractService mymContractService;
	
	@Autowired
    private MymRoomsService mymRoomsService;
	
	@Autowired
	private MymRooms2Service mymRooms2Service;
	
	@Autowired
    PanoplanBuildPlanService panoplanBuildPlanService;
	
	@Autowired
    PanoplanBuildPlanItemService panoplanBuildPlanItemService;
	
    @Autowired
    PanoplanBuildPlanItemDetailService panoplanBuildPlanItemDetailService;
	
    @Value("${buildPlan_url}")
	private String buildPlan_url;
	
	@Value("${buildPlan_file_path}")
	private String buildPlan_file_path;
    
	int SALE_ROOM_UPDATE_SIZE = 1000;
	
	@Override
	public R project(String apiVersion) {
		List<MdmProject> mdmProjectList = mdmService.queryProjectList();
		List<List> subList = ListUtils.getSubList(mdmProjectList, SALE_ROOM_UPDATE_SIZE);
		for (List list : subList) {
			List<MdmProject> insertList = (List<MdmProject>) list;
			projectService.insertBatch(insertList);
		}
		return ok();
	}
	
	@Override
	public R stage(String apiVersion) {
		List<MdmStage> mdmStageList = mdmService.queryMdmStageList();
		List<List> subList = ListUtils.getSubList(mdmStageList, SALE_ROOM_UPDATE_SIZE);
		for (List list : subList) {
			List<MdmStage> insertList = (List<MdmStage>) list;
			stageService.insertBatch(insertList);
		}
		return ok();
	}
	
	@Override
	public R buildArea(String apiVersion) {
		List<MdmBuildArea> gxcLdytDtolIST = mdmService.selectGxcLdytList();
		List<List> tempList = ListUtils.getSubList(gxcLdytDtolIST, SALE_ROOM_UPDATE_SIZE);
		for (List list : tempList) {
			List<MdmBuildArea> insertList = (List<MdmBuildArea>) list;
			buildAreaService.inserBatch(insertList);
		}
		return ok();
	}

	@Override
	public R groupBld(String apiVersion) {
		List<MdmGroupBld> mdmGroupBldList = mdmService.queryMdmGroupBldList();
		List<List> subList = ListUtils.getSubList(mdmGroupBldList, 1000);
		for (List list : subList) {
		   List<MdmGroupBld> saveList =(List<MdmGroupBld>)list;
		   groupBldService.inertBatch(saveList);
		}	
		return ok();
	}
	
	@Override
	public R partner(String apiVersion) {
		List<MdmProjectPatner> xmhzfList = mdmService.selectProjectPatnerList();
		List<List> tempList = ListUtils.getSubList(xmhzfList, SALE_ROOM_UPDATE_SIZE);
		for (List list : tempList) {
			List<MdmProjectPatner> insertList = (List<MdmProjectPatner>) list;
			projectPatnerService.insertPartnerList(insertList);
		}
		return ok();
	}
	
	
	@Override
	public R stagePartners(String apiVersion) {
		return ok(stagePartNersService.syncViewStagePartners());
	}

	@Override
	public R rooms(String apiVersion) {
		List<MymRooms> roomList = null;
		for(int i=0;i<13;i++) {
			roomList = mymRoomsService.selectAllRoomsFromMym(i);
			List<List> tempList = ListUtils.getSubList(roomList, SALE_ROOM_UPDATE_SIZE);
			for (List<MymRooms> list : tempList) {
				List<MymRooms> insertList = (List<MymRooms>) list;
				mymRoomsService.insertRoomsList(insertList);
				logger.info("月份："+i);
			}
		}
		logger.info("明源数据导出完成");
		return ok();
	}
	
	@Override
	public R rooms2(String apiVersion,String type) {
		List<MymRooms2> roomList = null;
		for(int i=0;i<13;i++) {
			roomList = mymRooms2Service.selectAllRoomsFromMym2(i);
			List<List> tempList = ListUtils.getSubList(roomList, SALE_ROOM_UPDATE_SIZE);
			for (List<MymRooms2> list : tempList) {
				List<MymRooms2> insertList = (List<MymRooms2>) list;
				mymRooms2Service.insertRoomsList(insertList,type);
				logger.info("月份："+i);
			}
		}
		logger.info("明源数据导出完成");
		return ok();
	}
    
	@Override
    public String allData(String apiVersion) {
        String returnStatus = "S";
        String returnMsg = "调用成功";
        String requestTime = null;
        String responseTime = null;
        String allDataInfo = getBuildPlan();
        logger.info("allData:",allDataInfo);
        try {
            requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
            JSONObject allDataObject = JSON.parseObject(allDataInfo);
            JSONArray data = allDataObject.getJSONArray("data");
            if (data.size() > 0){
                //第二层级
                Map<String,List<JSONObject>> groupDetailMap = null;
                List<JSONObject> groupDetailItemList = null;
                //第三层级
                Map<String,List<JSONObject>> nodeDetailMap = null;
                List<JSONObject> nodeDetailItemList = null;
                for (int i = 0;i < data.size();i ++){
                    JSONObject dataItem = data.getJSONObject(i);
                    JSONObject requestInfo = dataItem.getJSONObject("requestInfo");
                    JSONObject buildingPlan = requestInfo.getJSONObject("buildingPlan");
                    JSONObject buildingPlanInfoLine = buildingPlan.getJSONObject("buildingPlanInfoLine");
                    String id = UUIDUtils.create();
                    panoplanBuildPlanService.syncAllData(buildingPlanInfoLine,id);
                    //每循环一条单条数据都要清空二三层级对应的map，避免重复插入上一次循环存入的数据
                    groupDetailMap = new HashMap<>();
                    nodeDetailMap = new HashMap<>();

                    JSONArray groupDetail = buildingPlanInfoLine.getJSONArray("groupDetail");
                    if (groupDetail.size() > 0){
                        groupDetailItemList = new ArrayList<>();
                        String itemId = null;

                        for (int j = 0;j < groupDetail.size();j ++){
                            itemId = UUIDUtils.create();
                            JSONObject groupDetailItem = groupDetail.getJSONObject(j);
                            groupDetailItem.put("itemId",itemId);
                            groupDetailItemList.add(groupDetailItem);
                            JSONArray nodeDetail = groupDetailItem.getJSONArray("nodeDetail");
                            nodeDetailItemList = new ArrayList<>();
                            if (nodeDetail.size() > 0){
                                for (int z = 0;z < nodeDetail.size();z ++){
                                    JSONObject nodeDetailItem = nodeDetail.getJSONObject(z);
                                    nodeDetailItemList.add(nodeDetailItem);
                                }
                            }
                            nodeDetailMap.put(itemId,nodeDetailItemList);
                        }
                        //第三层级插入
                        panoplanBuildPlanItemDetailService.syncAllDataItemDetail(nodeDetailMap);
                        //第二层级插入
                        groupDetailMap.put(id,groupDetailItemList);
                        panoplanBuildPlanItemService.syncAllDataItem(groupDetailMap);
                    }
                }
            }
            responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
        } catch (Exception e) {
            returnStatus = "E";
            returnMsg = "调用失败";
        }
        logger.info("获取楼栋计划全量数据成功 "+new Date());
        return "{\"esbInfo\":{\"instId\":\"RVNCTXVsZUVTQi9MYW5kUHVibGlzaEZsb3cyMDE5LTA2LTExIDExOjQzOjQ0LjMzNg== \",\"returnStatus\":"+returnStatus+",\"returnCode\":\"A001-SMS\",\"returnMsg\":"+returnMsg+",\"requestTime\":"+requestTime+",\"responseTime\":"+responseTime+",\"attr1\":null,\"attr2\":null,\"attr3\":null}}";
    }
	
	private String getBuildPlan() {
		StringBuilder allDataInfo = new StringBuilder();
		HttpURLConnection conn = null;
		try {
			URL url = new URL(buildPlan_url);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(60 * 1000);
			conn.setReadTimeout(60 * 1000);
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			// 建立实际的连接
			conn.connect();
			// 定义 BufferedReader输入流来读取URL的响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = reader.readLine()) != null) {
				allDataInfo.append(line);
			}
			reader.close();
			reader = null;
		} catch (IOException e) {
			logger.error("=====请求异常 START=====\r\n" + buildPlan_url + "\r\n=====请求异常 END=====");
			log.error("###### errorMsg: ", e);
		} finally {
			if (conn != null) {
				conn.disconnect();
				conn = null;
			}
		}
		return allDataInfo.toString();
	}

	/**
	 * 全量拉取明源视图
	 */
	@Override
	public R mymContractView(String apiVersion) {
		//删除签约视图表
		mymContractService.deleteContract();
		List<MymContract> contractList = null;
		for(int i=0;i<13;i++) {
			contractList = mymService.selectAllContract(i);
			List<List> tempList = ListUtils.getSubList(contractList, SALE_ROOM_UPDATE_SIZE);
			for (List<MymContract> list : tempList) {
				List<MymContract> insertList = (List<MymContract>) list;
				mymService.insertContractList(insertList);
				logger.info("月份："+i);
			}
		}
		logger.info("明源签约视图数据增加完成");
		return ok();
	}
	
}
